package org.dam.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dam.entity.ArticleEntity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Author dam
 * @create 2024/8/5 9:36
 */
public class CsdnScoreUtil {

    /**
     * 查询质量分的地址
     */
    private static final String SCORE_URL = "https://bizapi.csdn.net/trends/api/v1/get-article-score";
    private static final String X_CA_KEY = "203930474";
    private static final String X_CA_NONCE = "9cf8f777-27fe-4a6b-a968-86c17c6ab787";
    private static final String X_CA_SIGNATURE = "ruA7Zl7QDFkIbJYd/uP5pfi9PA7ZAPcbZ9htV4wjbos=";
    private static final String X_CA_SIGNATURE_HEADERS = "x-ca-key,x-ca-nonce";
    private static final String X_CA_SIGNED_CONTENT_TYPE = "multipart/form-data";

    /**
     * 获取所有文章的质量分
     *
     * @param articleListObject
     * @return
     */
    public List<ArticleEntity> csdnScoreCheck(JSONObject articleListObject) {
        JSONObject articleListMes = articleListObject.getJSONObject("data");
        JSONArray jsonArray = (JSONArray) articleListMes.get("list");

        List<ArticleEntity> articleEntityList = new ArrayList<>();
        for (Object o : jsonArray) {
            JSONObject one = (JSONObject) o;
            articleEntityList.add(ArticleEntity.builder()
                    .url(String.valueOf(one.get("url")))
                    .title(String.valueOf(one.get("title")))
                    .build());
        }

        // 调用csdn接口查询所有的博客质量分
        HttpRequest post = HttpUtil.createPost(SCORE_URL)
                .header("accept", "application/json, text/plain, */*")
                .header("x-ca-key", X_CA_KEY)
                .header("x-ca-nonce", X_CA_NONCE)
                .header("x-ca-signature", X_CA_SIGNATURE)
                .header("x-ca-signature-headers", X_CA_SIGNATURE_HEADERS)
                .header("x-ca-signed-content-type", X_CA_SIGNED_CONTENT_TYPE);
        for (ArticleEntity articleEntity : articleEntityList) {
            post.form("url", articleEntity.getUrl());
            HttpResponse response = post.execute();
            if (response.isOk()) {
                JSONObject scoreMes = JSON.parseObject(response.body());
                ArticleEntity articleEntity2 = JSON.toJavaObject(scoreMes.getJSONObject("data"), ArticleEntity.class);
                articleEntity.setScore(articleEntity2.getScore());
                articleEntity.setPostTime(articleEntity2.getPostTime());
                System.out.println("名称:" + articleEntity.getTitle() + "\t质量分:" + articleEntity.getScore() + "\t发表时间:" + articleEntity.getPostTime());
            } else {
                System.err.println(articleEntity.getUrl() + "请求失败: " + response.getStatus());
            }
        }

        return articleEntityList;
    }

    /**
     * 读取json文件，获取文章标题和链接
     *
     * @throws Exception
     */
    public void getScoreByJson() throws Exception {
        String read = TxtUtil.read(new File("src/main/java/org/dam/input/article-list.json"), "utf-8");
        List<ArticleEntity> articleEntityList = csdnScoreCheck(JSON.parseObject(read));
        save(articleEntityList);
    }

    /**
     * 将检查到的质量信息存储到excel表格中
     *
     * @param scoreEntities
     * @throws IOException
     */
    public void save(List<ArticleEntity> scoreEntities) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        int rowIndex = 0;
        Row row = sheet.createRow(rowIndex++);
        row.createCell(0).setCellValue("文章名称");
        row.createCell(1).setCellValue("质量分");
        row.createCell(2).setCellValue("发布时间");

        // 按照分数升序排序
        Collections.sort(scoreEntities, ((o1, o2) -> {
            return Double.compare(o1.getScore(), o2.getScore());
        }));

        for (ArticleEntity article : scoreEntities) {
            row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(article.getTitle());
            row.createCell(1).setCellValue(article.getScore());
            row.createCell(2).setCellValue(article.getPostTime());
        }

        System.out.println("开始输出结果");
        FileOutputStream outputStream = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        try {
            outputStream = new FileOutputStream("src/main/java/org/dam/output/质量列表 " + simpleDateFormat.format(new Date()) + ".xlsx");
            workbook.write(outputStream);
            System.out.println("文件输出完成");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
